<template>
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page="page"
                 @row-del="rowDel"
                 v-model="form"
                 :permission="permissionList"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 :before-open="beforeOpen"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @on-load="onLoad">
                 <template slot-scope="{row}" slot="title">
                  {{row.commodityList?row.commodityList[0].title:'--'}}
                </template>
                <template slot-scope="{row}" slot="price">
                  {{row.commodityList?row.commodityList[0].price:'--'}} 元
                </template>
                 <template #menu="{row,index,size}">
                      <el-button v-if="(row.type==2&&row.verifyStatus==1)&&row.payStatus==1" type="text" :size="size"  @click="openRefund(row)">退押金</el-button>
                </template>
      </avue-crud>

      <el-dialog title="退押金"
             append-to-body
             :visible.sync="showDialog"
             top="5%"
             width="60%">
             <el-form ref="form1" :model="form1" label-width="80px">
              <el-form-item label="手机号">
               {{ form.phone }}
              </el-form-item>
              <el-form-item label="商品详情">
                {{ form.title }}
              </el-form-item>
              <el-form-item label="核销时间">
                {{ form.verifyTime }} 
              </el-form-item>
              <el-form-item label="商品押金">
                {{ form.price }} 元
              </el-form-item>
              <el-form-item label="延期费用">
                <el-input v-model="form.delayAmount"></el-input>
                <p style="color: #f33;font-size: 12px;margin: 0;">3小时免费，过后每一个小时-5元，扣完即止，自动计算</p>
              </el-form-item>
              <el-form-item label="损坏费用">
                <el-input v-model="form.destroyAmount"></el-input>
              </el-form-item>
              <el-form-item label="可退费用">
                ￥ ：{{ form.refundPrice || '0.00' }}
              </el-form-item>
              <el-form-item label="扣费备注">
                <el-input v-model="form.reason"  type="textarea" ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit">立即退回</el-button>
                <el-button @click="showDialog=false">取消</el-button>
              </el-form-item>
            </el-form>
      </el-dialog>
    </basic-container>
  </template>
  
  <script>
    import {getList,detail ,orderprocess} from "@/api/order/order";
    import { refund,generateUuid } from "@/api/WxPay/WxPay";
    import {mapGetters} from "vuex";
  
    export default {
      watch: {
        'form.delayAmount'() {
          let delayAmount=parseFloat(this.form.delayAmount) || 0
          let destroyAmount=parseFloat(this.form.destroyAmount) || 0
          let price=parseFloat(this.form.price) || 0
          this.form.refundPrice=price-(delayAmount + destroyAmount)
          if(this.form.refundPrice<0){
            this.form.refundPrice=0
          }
        },
        'form.destroyAmount'() {
          let delayAmount=parseFloat(this.form.delayAmount) || 0
          let destroyAmount=parseFloat(this.form.destroyAmount) || 0
          let price=parseFloat(this.form.price) || 0
          this.form.refundPrice=price-(delayAmount + destroyAmount)
          if(this.form.refundPrice<0){
            this.form.refundPrice=0
          }
        }
      },
      data() {
        return {
     
          showDialog:false,
          form: {},
          query: {
            type:''
          },
          loading: true,
          page: {
            pageSize: 10,
            currentPage: 1,
            total: 0
          },
          selectionList: [],
          option: {
            height: 'auto',
            calcHeight: 210,
            searchShow: true,
            searchMenuSpan: 6,
            tip: false,
            border: true,
            index: true,
            viewBtn: true,
            delBtn:false,
            addBtn:false,
            editBtn:false,
            selection: true,
            searchIcon:true,
            searchIndex:3,
            column: [
              {
                label: "手机号",
                prop: "phone",
                span: 24,
                search: true
              },
              {
                label: "商品名称",
                prop: "title",
                span: 24,
                search: true
              },{
                label: "商品价格",
                prop: "price",
                span: 24,
              },{
                label: "核销时间",
                prop: "verifyTime",
                span: 24,
              },{
                label: "延期费用",
                prop: "delayAmount",
                hide:true,
                span: 24,
              },{
                label: "损坏费用",
                prop: "destroyAmount",
                hide:true,
                span: 24,
              },{
                label: "已退费用",
                prop: "refundPrice",
                hide:true,
                span: 24,
              },{
                label: "扣费备注",
                prop: "reason",
                hide:true,
                span: 24,
              },{
                label: "订单类型",
                search: true,
                prop: "type",
                type: "select",
                span: 24,
                dicData: [{
                  label: '购买',
                  value: 1
                }, {
                  label: '租赁',
                  value: 2
                }]
              },{
                type: "select",
                label: "核销状态",
                search: true,
                prop: "verifyStatus",
                span: 24,
                dicData: [{
                  label: '待核销',
                  value: 0
                }, {
                  label: '已核销',
                  value: 1
                }, {
                  label: '无需核销',
                  value: -1
                }
                // , {
                //   label: '已归还',
                //   value: 2
                // }
              ]
              },{
                type: "select",
                label: "支付状态",
                search: true,
                prop: "payStatus",
                span: 24,
                dicData: [{
                  label: '已支付',
                  value: 1
                }, {
                  label: '未支付',
                  value: 2
                }, {
                  label: '已退款',
                  value:3
                }, {
                  label: '取消订单',
                  value:4
                }]
              }
              // ,{
              //   label: "订单流程",
              //   prop: "orderprocess",
              //   span: 24,
              //   hide:true
              // },
            ]
          },
          data: []
        };
      },
      computed: {
        ...mapGetters(["permission"]),
        permissionList() {
          return {
           
          };
        },
        ids() {
          let ids = [];
          this.selectionList.forEach(ele => {
            ids.push(ele.id);
          });
          return ids.join(",");
        }
      },
      methods: {
        hoursBetween(time1) {
          // 将时间字符串转换为Date对象
          var date1 = new Date(time1);
          var date2 = new Date();
        
          // 计算两个时间的时间戳差值
          var diff = Math.abs(date2.getTime() - date1.getTime());
        
          // 将差值转换为小时
          var hours = diff / (1000 * 60 * 60);
        
          // 返回结果
          return hours;
        },
        onSubmit(){
          generateUuid().then(res => {
            let outTradeNo=res.data.data
            let params={
              orderId:this.form.id,
              refundPrice:this.form.refundPrice,
              refundNum:outTradeNo,
              delayAmount:this.form.delayAmount,
              destroyAmount:this.form.destroyAmount,
              reason:this.form.reason
            }
            console.log(params)
            refund(params).then(res => {
              this.$message({
                type: "success",
                message: res.data.msg
              });
              if(res.data.success){
                  this.showDialog=false
              }
              this.onLoad(this.page);
            });
          });
        },
        rowSave(row, done, loading) {
          add(row).then(() => {
            done();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, error => {
            window.console.log(error);
            loading();
          });
        },
        rowUpdate(row, index, done, loading) {
          update(row).then(() => {
            done();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, error => {
            window.console.log(error);
            loading();
          });
        },
        rowDel(row) {
          this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              return remove(row.id);
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            });
        },
        searchReset() {
          this.query = {};
          this.onLoad(this.page);
        },
        searchChange(params, done) {
          this.query = params;
          this.page.currentPage = 1;
          this.onLoad(this.page, params);
          done();
        },
        selectionChange(list) {
          this.selectionList = list;
        },
        handleDelete() {
          if (this.selectionList.length === 0) {
            this.$message.warning("请选择至少一条数据");
            return;
          }
          this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              return remove(this.ids);
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.$refs.crud.toggleSelection();
            });
        },
        openRefund(row){
          detail(row.id).then(res => {
              let data=res.data.data
              data.delayAmount=0
              this.form = data;
             
              this.form.title=res.data.data.commodityList[0].title
              this.form.price=res.data.data.commodityList[0].price
              this.showDialog=true
              let time =this.hoursBetween(this.form.verifyTime)
            
              if(time<=3){
                this.form.delayAmount=0.00
              }
             
              if(time>3){
                let delayAmount= Math.ceil(time) -3
                delayAmount= delayAmount * 5
                if(delayAmount<0){
                  this.form.delayAmount = 0
                }else{
                  this.form.delayAmount=delayAmount
                }
               
              }
              
          });
        },
        beforeOpen(done, type) {
          if (["edit", "view"].includes(type)) {
            detail(this.form.id).then(res => {
              let data=res.data.data
              this.form = data;
              this.form.title=data.commodityList[0].title
              this.form.price=data.commodityList[0].price
              if(data.orderRefund&&JSON.stringify(data.orderRefund)!='{}'){
                this.form.delayAmount=data.orderRefund.delayAmount
                this.form.destroyAmount=data.orderRefund.destroyAmount
                this.form.reason=data.orderRefund.reason
              }
              console.log(this.form)
              // orderprocess({
              //   orderId:this.form.id
              // }).then(res => {

              // })
              
              
            });
          }
          done();
        },
        currentChange(currentPage) {
          this.page.currentPage = currentPage;
        },
        sizeChange(pageSize) {
          this.page.pageSize = pageSize;
        },
        onLoad(page, params = {}) {
          this.loading = true;
          getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
            const data = res.data.data;
            this.page.total = data.total;
            this.data = data.records;
            this.loading = false;
          });
        }
      }
    };
  </script>
  
  <style>
  </style>
  